# -*- coding: utf-8 -*-
import common.libs.Helper
from application import app, db, mail
from common.models.interview_comment import InterviewComment
from common.libs.SQLTransform import queryToDict
from common.models.bpm import Bpm
from common.models.formation import Formation
from common.models.interview_goal import InterviewGoal
from common.libs.Helper import unduplicate
from dingtalk import SecretClient, model
from flask import Blueprint, request, make_response, redirect
from common.models.user import User
from common.models.resigntalk import ResignTalk
from sqlalchemy import distinct
import json, requests
from sqlalchemy import and_, or_
import urllib.parse
from common.libs.DataHelper import getCurrentTime, getCurrentDate
from config.dingtalk_setting import AppKey, AppSecret, AgentId, role_hr
from flask_mail import Mail, Message
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, ops_render
from common.libs.Helper import dateafter
from common.libs.Helper import dingtalkpost

resign_page = Blueprint("resign_page", __name__)

##连接
client = SecretClient(AppKey, AppSecret)  # 新 access_token 获取方式


@resign_page.route('/getresigntalkinfo', methods=['GET', 'POST'])
def getresigntalkinfo():
    id = request.json.get('userid')
    print(id)
    resign = ResignTalk.query.filter_by(userid=id).first()
    id=resign.id
    reason = resign.reason.split(',')
    improve=resign.improve.split(',')
    isreserve=resign.isreserve
    q1 = resign.q1
    q2 = resign.q2
    q3 = resign.q3
    q4 = resign.q4
    q5 = resign.q5
    q6 = resign.q6
    username=resign.userinfo.name
    hrname=resign.hrinfo.name
    hrcomment=resign.hrcomment
    hrimprove=resign.hrimprove
    resigninfo={"id":id,"reason":reason,"improve":improve,"isreserve":isreserve,"q1":q1,"q2":q2,"q3":q3,"q4":q4,"q5":q5,"q6":q6,"hrcomment":hrcomment,"hrimprove":hrimprove,"username":username,"hrname":hrname}
    print(resigninfo)
    return json.dumps(resigninfo, ensure_ascii=False)


@resign_page.route('/sendresigntalkinput', methods=['GET', 'POST'])
def sendresigntalk():
    userlist = request.json.get("userid")
    userid = userlist[0]
    user = User.query.filter_by(userid=userid).first()

    # userlist = userid.split("。")
    posterid = request.json.get("postid")

    user1 = User.query.filter_by(userid=userid).first()
    username = user1.name
    user2 = User.query.filter_by(id=posterid).first()
    hrname = user2.name

    base_url = 'http://101.132.227.54:88/resigninput?posterid=' + posterid + "&userid=" + str(user.id)
    encodeurl = urllib.parse.quote(base_url)

    dingtalkurl = "dingtalk://dingtalkclient/action/openapp?corpid=ding976485bf6d4d1f69acaaa37764f94726&container_type=work_platform&app_id=0_1517315486&redirect_type=jump&redirect_url=" + encodeurl
    normalurl = "dingtalk://dingtalkclient/page/link?url=" + encodeurl + "&pc_slide=true"

    msg = {
        "msgtype": "action_card",
        "action_card": {
            "title": "离职访谈",
            "markdown": "![](http://upload.guanzhuoran.cn/resigntalk.png) \n   #### 受访人：" + username + "  \n   #### 访谈HR：" + hrname,
            "btn_orientation": "1",
            "btn_json_list": [
                # {
                #     "title": "查看简历(PC)",
                #     "action_url": dingtalkurl,
                # },
                {
                    "title": "查看",
                    "action_url": normalurl,
                },

            ]
        }
    }
    print(msg)
    a = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)

    return json.dumps("访谈已成功推送", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)


@resign_page.route('/sendtoother', methods=['GET', 'POST'])
def sendtoother():
    leaderid = request.json.get("leaderid")
    leaderidlist = leaderid.split("。")
    userid = request.json.get("userid")
    posterid = request.json.get("postid")
    print(leaderid)
    print(userid)

    user = User.query.filter_by(id=userid).first()
    username = user.name
    user2 = User.query.filter_by(id=posterid).first()
    hrname = user2.name

    base_url = 'http://101.132.227.54:88/resignread?userid=' + str(user.id)+'&posterid='+posterid
    encodeurl = urllib.parse.quote(base_url)

    dingtalkurl = "dingtalk://dingtalkclient/action/openapp?corpid=ding976485bf6d4d1f69acaaa37764f94726&container_type=work_platform&app_id=0_1517315486&redirect_type=jump&redirect_url=" + encodeurl
    normalurl = "dingtalk://dingtalkclient/page/link?url=" + encodeurl + "&pc_slide=true"

    msg = {
        "msgtype": "action_card",
        "action_card": {
            "title": "离职访谈",
            "markdown": "![](http://upload.guanzhuoran.cn/resigntalk.png) \n   #### 受访人：" + username + "  \n   #### 访谈HR：" + hrname,
            "btn_orientation": "1",
            "btn_json_list": [
                # {
                #     "title": "查看简历(PC)",
                #     "action_url": dingtalkurl,
                # },
                {
                    "title": "查看",
                    "action_url": normalurl,
                },

            ]
        }
    }
    print(msg)
    a = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=leaderidlist)

    return json.dumps("访谈已成功推送", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)


@resign_page.route('/postresigntalk', methods=['GET', 'POST'])
def postresigntalk():
    newdata = request.json.get("form")
    userid = request.json.get("userid")
    postid = request.json.get("postid")
    print(newdata)

    resigntalk = ResignTalk()
    resigntalk.reason = str(newdata['reason']).replace('[', '').replace(']', '').replace(' ', '').replace("'", "")
    resigntalk.improve = str(newdata['improve']).replace('[', '').replace(']', '').replace(' ', '').replace("'", "")
    resigntalk.isreserve = newdata['isreserve']
    if 'q1' in newdata:
        resigntalk.q1 = newdata['q1']
    else:
        resigntalk.q1 = "无"
    if 'q2' in newdata:
        resigntalk.q2 = newdata['q2']
    else:
        resigntalk.q2 = "无"
    if 'q3' in newdata:
        resigntalk.q3 = newdata['q3']
    else:
        resigntalk.q3 = "无"
    if 'q4' in newdata:
        resigntalk.q4 = newdata['q4']
    else:
        resigntalk.q4 = "无"
    if 'q5' in newdata:
        resigntalk.q5 = newdata['q5']
    else:
        resigntalk.q5 = "无"
    if 'q6' in newdata:
        resigntalk.q6 = newdata['q6']
    else:
        resigntalk.q6 = "无"
    resigntalk.hrid = postid
    resigntalk.userid = userid
    resigntalk.date = getCurrentTime()

    db.session.add(resigntalk)
    db.session.commit()

    user=User.query.filter_by(id=userid).first()
    postuser=User.query.filter_by(id=postid).first()
    username=user.name
    posteruserid=postuser.userid
    posterlist = posteruserid.split("。")

    msg = {
        "msgtype": "text",
        "text": {
            "content": "离职人员【" + username + "】已完成离职访谈内容填写，请前往eHR进行后续手续办理"
        }
    }
    dingtalksn = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=posterlist)

    return json.dumps("提交成功", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)


@resign_page.route('/posthrcomment', methods=['GET', 'POST'])
def posthrcomment():
    id = request.json.get("id")
    hrcomment = request.json.get("hrcomment")
    hrimprove = request.json.get("hrimprove")

    resigntalk = ResignTalk.query.filter_by(id=id).first()

    resigntalk.hrcomment = hrcomment
    resigntalk.hrimprove = hrimprove

    db.session.commit()
    return json.dumps("提交成功", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)
